/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pl.droidsonroids.gif.gifsample.slice;

import pl.droidsonroids.gif.gifsample.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import pl.droidsonroids.gif.GifOptions;
import pl.droidsonroids.gif.GifTexImage2D;
import pl.droidsonroids.gif.InputSource;
import pl.droidsonroids.gif.gifsample.LogUtil;
import pl.droidsonroids.gif.gifsample.opengl.GifTexImage2dProgram;
import pl.droidsonroids.gif.gifsample.opengl.SurfaceCallback;

import java.io.IOException;

/**
 * Gif2dSlice
 */
public class Gif2dSlice extends AbilitySlice {
    private static final String TAG = Gif2dSlice.class.getName();
    GifTexImage2D image2D;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);

        super.setUIContent(ResourceTable.Layout_gif_2d);
        try {
            initView();
        } catch (IOException | DataAbilityRemoteException e) {
            LogUtil.error(TAG, "IOException or DataAbilityRemoteException");
        }
    }

    private void initView() throws IOException, DataAbilityRemoteException {
        SurfaceProvider surface = (SurfaceProvider) findComponentById(ResourceTable.Id_surface);
        surface.setVisibility(Component.VISIBLE);
        surface.pinToZTop(true);
        InputSource.AssetSource source = new InputSource.AssetSource(getResourceManager()
            .getRawFileEntry("entry/resources/rawfile/anim_flag_england.gif"), "");
        GifOptions options = new GifOptions();
        options.setInIsOpaque(true);
        image2D = new GifTexImage2D(source, options);
        image2D.startDecoderThread();
        surface.getSurfaceOps().get().addCallback(new SurfaceCallback(new GifTexImage2dProgram(image2D)));
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
